package com.xuanzheng.company.servlet;

import com.xuanzheng.company.entity.SystemApplication;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.SystemApplicationService;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;
import com.xuanzheng.company.service.impl.SystemApplicationServiceImpl;
import com.xuanzheng.company.service.impl.UserServiceImpl;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * 监听器：当系统启动时，检查是否有已批准但尚未创建公司的系统申请
 */
@WebListener
public class SystemApplicationApprovalListener implements ServletContextListener {
    private final SystemApplicationService applicationService = new SystemApplicationServiceImpl();
    private final UserService userService = new UserServiceImpl();
    private final CompanyService companyService = new CompanyServiceImpl();
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("系统启动，检查系统申请并创建公司...");
        
        try {
            // 获取已通过的系统申请
            List<SystemApplication> approvedApplications = applicationService.getApplicationsByStatus(1);
            
            for (SystemApplication application : approvedApplications) {
                // 检查用户是否已有公司
                User user = userService.findById(application.getUserId());
                if (user != null && user.getRole() == 1 && user.getCompanyId() == null) {
                    // 用户是公司负责人但还没有创建公司，自动创建
                    String companyId = companyService.createCompanyFromApproval(user);
                    if (companyId != null) {
                        System.out.println("已为用户 " + user.getName() + " (ID: " + user.getId() + ") 创建公司，公司ID: " + companyId);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("自动创建公司失败: " + e.getMessage());
        }
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 系统关闭时不需要特殊处理
    }
} 